import Vue from 'vue'
import qs from 'qs'
import router from '@/router'
//import store from '@/store'
import {login} from '../../api/wechat'
import wechatAuth from '../wechatauth/auth'


Vue.use(wechatAuth, {
  appid: 'wxf56101a7941a5a61'
})

router.beforeEach(async (to, from, next) => {
  var loginStatus = localStorage.getItem('loginStatus') ;// store.state.loginStatus
  if(loginStatus==null){
    loginStatus=0;
    localStorage.setItem('tableId',to.query.tableId)
  }
  else {
    loginStatus=parseInt(loginStatus)
  } 

  var token = localStorage.getItem("token");
  if(loginStatus==2 && (!token || token=="")){
    loginStatus=0;
  }

  switch (loginStatus) {
    case 0:
      wechatAuth.redirect_uri = processUrl()
      localStorage.setItem('loginStatus',1)
      //await store.dispatch('setLoginStatus', 1)
      window.location.href = wechatAuth.authUrl
      break
    case 1:
      try {
        wechatAuth.returnFromWechat(to.fullPath)
        await processLogin(wechatAuth.code)
        next()
      } catch (err) {
        localStorage.setItem('loginStatus',0)
        //await store.dispatch('setLoginStatus', 0)
        next()
      }
      break
    case 2:
      next()
      break
    default:
      break
  }
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title
  }
})

/**
 * 处理url链接
 * @returns {string}
 */
function processUrl () {
  const url = window.location.href
  // 解决多次登录url添加重复的code与state问题
  const urlParams = qs.parse(url.split('?')[1])
  let redirectUrl = url
  if (urlParams.code && urlParams.state) {
    delete urlParams.code
    delete urlParams.state
    const query = qs.stringify(urlParams)
    if (query.length) {
      redirectUrl = `${url.split('?')[0]}?${query}`
    } else {
      redirectUrl = `${url.split('?')[0]}`
    }
  }
  return redirectUrl
}

/**
 * 处理登录
 * @param code
 * @returns {Promise<any>}
 */
function processLogin (code) {
  // const data = {
  //   code,
  // }
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve, reject) => {
    try {
      const { isSuccess,returnData ,message} = await login(code)
     
     // await store.dispatch('setLoginStatus', 2)
      //await store.dispatch('setAccessToken', accessToken)
      //await store.dispatch('setUserInfo', returnData.userInfo)

      if(isSuccess){
        localStorage.setItem("token",returnData.token)
        localStorage.setItem('loginStatus',2)

        if(returnData.isNeedFinishInfo) //是否需要完善信息
        {
          
              //TOOD:跳转信息完善界面
        }
      }
      else{
        localStorage.setItem('loginStatus',0)
        console.log(message)
      }

      
      resolve({ status: 1, data: '登录成功' })
    } catch (err) {
      reject(err)
    }
  })
}